package com.major.huffman.huffmancode;

import java.io.*;
import java.util.*;

public class HuffmanCodeMain {

    public static void main(String[] args) {
//        String c = "can you can a can as a can canner can a can.";
//        byte[] bytes = c.getBytes();
//
//        // 进行赫夫曼编码
//        byte[] code = huffmanZip(bytes);
//        //System.out.println(bytes.length);
//        //System.out.println(code.length);
//
//        // 解码
//        byte[] unCode = deCode(huffmanCodes, code);
//        System.out.println(new String(unCode));

        // 测试byte转二进制
        String bitString = byteToBitString(true, (byte) -48);
        //System.out.println(bitString);

//        String srcFile = "D:\\test.jpg";
//        String desFile = "D:\\test.zip";
//        zipFile(srcFile, desFile);

        String zipFile = "D:\\test.zip";
        String destFile = "D:\\test2.jpg";
        unZipFile(zipFile, destFile);

    }

    // 解压压缩文件
    private static void unZipFile(String zipFile, String destFile) {
        // 输入流
        InputStream inputStream = null;
        // 对象输入流
        ObjectInputStream objectInputStream = null;
        // 文件输出流
        OutputStream outputStream = null;

        try {
            // 创建文件输入流
            inputStream = new FileInputStream(zipFile);
            // 创建和输入流关联的对象输入流
            objectInputStream = new ObjectInputStream(inputStream);

            // 读取byte数组 huffmanBytes
            byte[] huffmanBytes = (byte[]) objectInputStream.readObject();
            // 读取huffman编码表
            Map<Byte, String> codes = (Map<Byte, String>) objectInputStream.readObject();

            // 解码
            byte[] bytes = deCode(codes,huffmanBytes);
            // 写出到目标文件
            outputStream = new FileOutputStream(destFile);
            // 写数据到文件
            outputStream.write(bytes);

        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            if (objectInputStream != null){
                try {
                    objectInputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null){
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    // 压缩文件
    private static void zipFile(String srcFile, String desFile) {
        // 创建输出流
        OutputStream outputStream = null;

        // 创建输入流
        FileInputStream inputStream = null;
        ObjectOutputStream objectOutputStream = null;
        try {
            inputStream = new FileInputStream(srcFile);
            // 创建和原文件大小一样的byte[]
            byte[] srcByte = new byte[inputStream.available()];
            // 读到数组里
            inputStream.read(srcByte);
            // 对原文件压缩
            byte[] huffmanZipByte = huffmanZip(srcByte);

            // 创建输出流，存放压缩文件
            outputStream = new FileOutputStream(desFile);

            // 创建和文件输出流关联的对象流
            objectOutputStream = new ObjectOutputStream(outputStream);
            //把 赫夫曼编码后的字节数组写入压缩文件
            objectOutputStream.writeObject(huffmanZipByte);
            // 这里我们以对象流的方式写入 赫夫曼编码，是为了以后我们恢复源文件时使用
            // 注意一定要把赫夫曼编码 写入压缩文件
            objectOutputStream.writeObject(huffmanCodes);

        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (objectOutputStream != null) {
                try {
                    objectOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStream != null) {
                try {
                    outputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }

    // 解码
    private static byte[] deCode(Map<Byte, String> huffmanCodes, byte[] code) {
        // 转换成二进制的字符串
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < code.length; i++) {
            byte temp = code[i];
            boolean isLast = (i == code.length - 1);
            String bitString = byteToBitString(!isLast, temp);
            builder.append(bitString);
            //System.out.print(bitString);
        }

        // 解码
        // 反转huffman表
        Map<String, Byte> huffmanDecodes = new HashMap<>();
        for (Map.Entry<Byte, String> entry : huffmanCodes.entrySet()) {
            huffmanDecodes.put(entry.getValue(), entry.getKey());
        }

        // 存放byte
        List<Byte> list = new ArrayList<>();
        for (int i = 0; i < builder.length(); ) {

            boolean isNotExist = true;
            int count = 1;
            Byte val = null;

            while (isNotExist) {
                // 没找到就继续往下找
                String key = builder.substring(i, i + count);
                val = huffmanDecodes.get(key);
                if (val == null) {
                    count++;
                } else {
                    isNotExist = false;
                }
            }
            list.add(val);
            i += count;
        }

        byte[] unCode = new byte[list.size()];
        for (int i = 0; i < list.size(); i++) {
            unCode[i] = list.get(i);
        }
        return unCode;
    }

    // 将一个byte 转换成二进制的字符串
    private static String byteToBitString(boolean isNotLast, byte code) {

        int temp = code;
        // 如果是正数，补高位。除了最后一个byte
        if (isNotLast) {
            // 按位或
            temp |= 256;
        }
        // 得到temp对应的二进制的补码
        String s = Integer.toBinaryString(temp);
        if (isNotLast) {
            return s.substring(s.length() - 8);
        } else {
            return s;
        }
    }


    // 进行赫夫曼编码压缩
    private static byte[] huffmanZip(byte[] bytes) {

        // 统计每一个byte出现的次数，并放入集合中
        List<Node> nodeList = getNodes(bytes);
        //System.out.println(nodeList);

        // 创建赫夫曼树
        Node huffmanTree = createHuffmanTree(nodeList);
        //preOrder(huffmanTree);

        // 创建赫夫曼编码表
        Map<Byte, String> huffmanCodes = getCodes(huffmanTree);
        //System.out.println(huffmanCodes);

        // 编码
        byte[] code = zip(bytes, huffmanCodes);
        System.out.println(Arrays.toString(code));
        return code;
    }

    //                  对原始数组进行编码 ↑          通过赫夫曼编码表 ↑
    private static byte[] zip(byte[] bytes, Map<Byte, String> huffmanCodes) {
        // bytes ---- huffmanCodes ----> string
        StringBuilder codeBuilder = new StringBuilder();
        for (byte b : bytes) {
            // ↑ 101001...
            codeBuilder.append(huffmanCodes.get(b));
        }

        System.out.println(codeBuilder);

        // 得到数组长度
        // int len = (stringBuilder.length() + 7) / 8;
        int len;
        if (bytes.length % 8 == 0) {
            len = codeBuilder.length() / 8;
        } else {
            len = codeBuilder.length() / 8 + 1;
        }

        //  创建编码后的数组,计算机可以传输的字节
        byte[] codeByte = new byte[len];
        // 记录是第几个数组
        int index = 0;
        for (int i = 0; i < codeBuilder.length(); i += 8) {
            String tempByte;
            // 如果最后超过了字符串的长度
            if (i + 8 > codeBuilder.length()) {
                tempByte = codeBuilder.substring(i);
            } else {
                tempByte = codeBuilder.substring(i, i + 8);
            }
            // 将截取到的8位 转换成byte 放进数组中
            codeByte[index] = (byte) Integer.parseInt(tempByte, 2);
            index++;
        }
        return codeByte;
    }

    //          ↑数据   ↑路径
    static Map<Byte, String> huffmanCodes = new HashMap<>();
    static StringBuilder builder = new StringBuilder();

    // 生成赫夫曼树对应的赫夫曼编码表
    private static Map<Byte, String> getCodes(Node root) {
        if (root == null) {
            return null;
        } else {
            // 处理左子树
            getCodes(root.left, "0", builder);
            // 处理右子树
            getCodes(root.right, "1", builder);
            return huffmanCodes;
        }
    }

    private static void getCodes(Node node, String path, StringBuilder builder) {
        StringBuilder builder1 = new StringBuilder(builder);
        builder1.append(path);
        // node 等于 null，说明上一个node是叶子结点，不做处理
        if (node != null) {
            // data 等于 null，说明该结点不是叶子结点，继续递归
            if (node.data == null) {
                getCodes(node.left, "0", builder1);
                getCodes(node.right, "1", builder1);
            }
            // 找到叶子结点
            else {
                huffmanCodes.put(node.data, builder1.toString());
            }
        }
    }

    // 前序遍历
    public static void preOrder(Node root) {
        if (root != null) {
            root.proOrder();
        } else {
            System.out.println("空树，不能遍历");
        }
    }

    // 创建huffman树
    private static Node createHuffmanTree(List<Node> nodeList) {
        // 循环处理
        while (nodeList.size() > 1) {
            // 排序
            Collections.sort(nodeList);
            // 取权值小的两个
            Node left = nodeList.get(0);
            Node right = nodeList.get(1);
            // 得到新树
            Node parent = new Node(null, left.weight + right.weight);
            parent.left = left;
            parent.right = right;
            // 删除原来的两个
            nodeList.remove(left);
            nodeList.remove(right);
            // 新树加入集合
            nodeList.add(parent);
        }
        return nodeList.get(0);
    }

    // byte数组转化为Node集合
    private static List<Node> getNodes(byte[] bytes) {

        // 遍历bytes，统计每一个byte出现的次数===> Map[key,value]
        Map<Byte, Integer> counts = new HashMap<>();
        for (byte byt : bytes) {
            Integer count = counts.get(byt);
            if (count == null) {        // 第一次出现
                counts.put(byt, 1);
            } else {                    // 不是第一次，加一
                counts.put(byt, count + 1);
            }
        }

        // 把带有byte及其出现次数的map 转化为node集合，
        //                            key-->byte-->data
        //                            value-->Integer-->weight
        List<Node> nodeList = new ArrayList<>();
        for (Map.Entry<Byte, Integer> entry : counts.entrySet()) {
            Node node = new Node(entry.getKey(), entry.getValue());
            nodeList.add(node);
        }
        return nodeList;
    }
}
